import mod_vector,math

def generateLine(point1,point2,version=None,removePoint1=True):
    x0,y0 = point1
    x1,y1 = point2
    points = []
    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1
    reversed = x0 > x1
    if reversed:
        x0, x1 = x1, x0
        y0, y1 = y1, y0
    if y0 < y1:
        ystep = 1
    else:
        ystep = -1
    deltax = x1 - x0
    deltay = abs(y1 - y0)
    if version == None:
        error = -(deltax / 2)
    elif deltax == 0:
        error = 0
    else:
        if version >= deltax:
            return None
        offset = (version+1) / 2
        if version % 2 == 0:
            offset = -offset
        error = (deltax/2) + offset
        error = -(error % deltax)
    y = y0
    for x in range(x0, x1+1):
        if steep:
            points.append((y,x))
        else:
            points.append((x,y))   
        error = error + deltay
        if error > 0:
            y = y + ystep
            error = error - deltax
    if removePoint1:
        points.remove(point1)
    if reversed:
        points.reverse()
    return points

#def findUnobstructedLine(level,origin,target):
#    line = generateLine(origin,target)
#    wallFree = True
#    for space in line[:-1]:
#        if space in level.entityMap and level.entityMap[space].blocksBullets:
#            wallFree = False
#            break
#    return line,wallFree

def findUnobstructedLine(level,origin,target):
    version = 0
    firstLine = None
    
    while 1:
        line = generateLine(origin,target,version)
        if not line:
            break
        #print 'Trying version '+str(version)
        if not firstLine:
            firstLine = line
                
        wallFree = True
        for space in line[:-1]:
            if space in level.entityMap and level.entityMap[space].blocksBullets:
                wallFree = False
                break
        if wallFree:
            return line,True
        version += 1
    return firstLine,False

def inRange(level,origin,target):
    return findUnobstructedLine(level,origin, target)[1]
        
def getBulletLine(level,origin,target):
    return findUnobstructedLine(level,origin, target)[0]

def getDistance(point1,point2):
    vector = mod_vector.subtractVectors(point1,point2)
    return math.hypot(vector[0],vector[1])